package org.lds.hotkey.common.autoconfigure;

import org.hibernate.validator.HibernateValidator;
import org.lds.hotkey.common.autoconfigure.etcd.EtcdClient;
import org.lds.hotkey.common.autoconfigure.etcd.EtcdProperties;
import org.lds.hotkey.common.autoconfigure.etcd.EtcdService;
import org.lds.hotkey.common.autoconfigure.spring.SpringUtil;
import org.lds.hotkey.common.autoconfigure.cache.LocalCacheFactory;
import org.lds.hotkey.common.autoconfigure.cache.caffeine.CaffeineLocalCacheFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.validation.Validation;
import javax.validation.Validator;

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties({EtcdProperties.class})
public class CommonAutoConfiguration {
    private final EtcdProperties etcdProperties;

    public CommonAutoConfiguration(EtcdProperties etcdProperties) {
        this.etcdProperties = etcdProperties;
    }

    @Bean
    public EtcdService etcdService() {
        EtcdClient etcdClient = new EtcdClient(etcdProperties.getEndpoints());
        return new EtcdService(etcdClient);
    }

    @Bean
    public SpringUtil springUtil() {
        return new SpringUtil();
    }

    @Bean
    public Validator validator() {
        return Validation.byProvider(HibernateValidator.class)
                .configure()
                .failFast(true)
                .buildValidatorFactory()
                .getValidator();
    }

    @Bean
    public LocalCacheFactory localCacheFactory() {
        return new CaffeineLocalCacheFactory();
    }

}
